package atest.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.log4j.Logger;

import java.io.PrintWriter;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author : zenghua
 * @version : v0.1 SqlScriptUtils.java
 * @since : 2018/5/18 15:38
 */
public class SqlScriptUtils {
	public static final Logger LOGGER = Logger.getLogger(SqlScriptUtils.class);

	public static void createBaseScript() {
		Connection conn = null;

		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mybatis?serverTimezone=Asia/Shanghai", "root", "root");

			Reader reader = Resources.getResourceAsReader("atest/sql/baseDB.sql");

			ScriptRunner runner = new ScriptRunner(conn);
			runner.setLogWriter(null);
			runner.setErrorLogWriter(new PrintWriter(System.err));
			runner.runScript(reader);
			conn.commit();
			reader.close();
		} catch (Exception e) {
			LOGGER.error("初始化脚本异常", e);
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					LOGGER.error("关闭数据库异常", e);
				}
			}
		}
	}
}
